package com.drinkian.authentication.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.drinkian.authentication.entity.po.User;
import com.drinkian.authentication.mapper.UserMapper;
import com.drinkian.authentication.service.IRegisterService;
import com.drinkian.entity.RequestResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Objects;

@Service
public class RegisterServiceImpl implements IRegisterService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public RequestResult handleRegister(User user) {
        if (!Objects.isNull(user)
                && !Objects.isNull(user.getUsername())
                && !Objects.isNull(user.getPassword())
                && !Objects.isNull(user.getCertificate())
                && !Objects.isNull(user.getEmail())) {
            user.setPassword(new BCryptPasswordEncoder().encode(user.getPassword()));
            QueryWrapper<User> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("username",user.getUsername());
            User checkHasRegistered = userMapper.selectOne(queryWrapper);
            int insert = 0;
            if(checkHasRegistered != null) {
                return new RequestResult(HttpStatus.BAD_REQUEST.value(), "该账号已经申请过了");
            }else{
                user.setNickname(user.getUsername());
                insert = userMapper.insert(user);
            }
            if(insert > 0) {
                return new RequestResult(HttpStatus.OK.value(), "提交成功，请等待审核邮件！");
            }
        }
        return new RequestResult(HttpStatus.BAD_REQUEST.value(), "参数有误！");
    }
}
